/* INCLUDES ******************************************************************/

#include "ses_lcdDriver.h"
#include "ses_common.h"

/* FUNCTION DEFINITION *******************************************************/

/**
 * Initializes  LCD
 */
void lcdDriver_init() {
	DDR(DISPLAY_CS_PORT) |= (1 << DISPLAY_CS_PIN); //declare pins as outputs.
	DDR(DISPLAY_A0_PORT) |= (1 << DISPLAY_A0_PIN);
	DDR(DISPLAY_RD_PORT) |= (1 << DISPLAY_RD_PIN);
	DDR(DISPLAY_WR_PORT) |= (1 << DISPLAY_WR_PIN);
	DISPLAY_RD_PORT |= (1 << DISPLAY_RD_PIN);   //set the value of WR and RD to 1
	DISPLAY_WR_PORT |= (1 << DISPLAY_WR_PIN);
}

/**
 * Selects one controller of the LCD
 *
 * @param sel	selected controller (either 0 or 1)
 */
void lcdDriver_selectController(uint8_t sel) {
	if (sel == 1)
		DISPLAY_CS_PORT |= (1 << DISPLAY_CS_PIN);
	if (sel == 0)
		DISPLAY_CS_PORT &= ~(1 << DISPLAY_CS_PIN);
}

/**
 * Writes a command to the selected LCD controller
 *
 * @param	a byte to write
 */
void lcdDriver_writeCommand(uint8_t data) {
	DDR(DISPLAY_DATA_PORT) = 0xff;
	DISPLAY_A0_PORT &= ~(1 << DISPLAY_A0_PIN);
	DISPLAY_WR_PORT &= ~(1 << DISPLAY_WR_PIN);
	DISPLAY_DATA_PORT = data;
	_delay_us(1);
	DISPLAY_WR_PORT |= (1 << DISPLAY_WR_PIN);

}

/**
 * Writes a byte into the RAM of the selected LCD controller
 *
 * @param data	a byte to write
 */
void lcdDriver_writeData(uint8_t data) {
	DDR(DISPLAY_DATA_PORT) = 0xff;
	DISPLAY_A0_PORT |= (1 << DISPLAY_A0_PIN);
	DISPLAY_WR_PORT &= ~(1 << DISPLAY_WR_PIN);
	DISPLAY_DATA_PORT = data;
	_delay_us(1);
	DISPLAY_WR_PORT |= (1 << DISPLAY_WR_PIN);

}

/**
 * Reads status byte from  selected LCD controller
 *
 * @return return the state of selected LCD controller
 */
uint8_t lcdDriver_readStatus() {
	uint8_t temp;
	DDR(DISPLAY_DATA_PORT) = 0;
	DISPLAY_A0_PORT &= ~(1 << DISPLAY_A0_PIN);
	DISPLAY_RD_PORT &= ~(1 << DISPLAY_RD_PIN);
	_delay_us(1);
	temp =PIN( DISPLAY_DATA_PORT);
	DISPLAY_RD_PORT |= (1 << DISPLAY_RD_PIN);
	return temp;
}

